<?php

namespace app\api\controller;

use addons\epay\library\Service;
use addons\third\model\Third;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use app\common\model\Post;
use app\common\model\Recharge;
use app\common\model\UserComplaint;
use app\common\model\UserIncome;
use app\common\model\UserIncomeLog;
use app\common\model\UserPost;
use app\common\model\UserRecharge;
use app\common\model\UserVip;
use Exception;
use fast\Random;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'login1'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        Hook::add('vip','app\\common\\behavior\\User');
        Hook::listen('vip');
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['data' => $this->auth->getUserinfo()]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login1()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $account = '963861306@qq.com';
        $password = '123456';
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $code = $this->request->param('code');
        $nickname = $this->request->param('nickname');
        $avatar = $this->request->param('avatar');
        if (!$code) {
            $this->error('code不能为空');
        }

        $openid = $this->auth->getOpenid($code);

        Db::startTrans();
        try {
            //第三方
            $model = new Third();
            $info = $model->where(['openid' => $openid])->find();

            if ($info) {
                $userMoel = \app\common\model\User::get($info->user_id);
                $userMoel->save([
                    'nickname' => $nickname,
                    'avatar' => $avatar
                ]);
                $this->auth->direct($info->user_id);
            }else {
                $ret = $this->auth->register($nickname, '123456', '', $nickname, ['avatar' => $avatar]);
                if($ret) {
                    $model->save([
                        'user_id' => $this->auth->id,
                        'platform' => '',
                        'apptype' => 'wxMiniProgram',
                        'openid' => $openid,
                        'openname' => $nickname,
                    ]);
                }else {
                    throw new Exception($this->auth->getError());
                }
            }
            Db::commit();
        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Sign up successful'), $data);
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    //投诉
    public function complaint()
    {
        $data = $this->request->post();
        $rule = [
            'description' => 'require',
            'username' => 'require',
            'package_id' => 'require',
        ];
        $msg = [
            'description.require' => '投诉原因不为空',
            'username.require' => '用户名不为空',
            'package_id.require' => '套餐名称不为空',
        ];
        $validate = new \think\Validate($rule, $msg);
        $res = $validate->check($data);
        if ($res === false) {
            $this->error($validate->getError());
        }
        Db::startTrans();
        try {
            $data['user_id'] = $this->auth->id;
            $package = \app\common\model\Package::get($data['package_id']);
            $data['staff_id'] = $package->staff_id;

            UserComplaint::create($data);
            Db::commit();
        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('投诉成功');

    }
    //推广记录
    public function agentlog()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit',LIMIT);

        $list =  $this->model->where(['status' => 'normal'])->order('id desc')->paginate($limit,false,['page' => $page]);

        $ret = true;
        if ($ret) {
            $this->success('投诉成功');
        } else {
            $this->error('投诉失败');
        }
    }
    //收益明细
    public function incomelog()
    {
        $ret = true;
        if ($ret) {
            $this->success('投诉成功');
        } else {
            $this->error('投诉失败');
        }
    }
    //开通发帖
//    public function setpost()
////    {
////        //判断用户开通会员
////        $user = $this->auth->getUser();
////        if($user->level <= 1) {
////            $this->error('请开通会员');
////        }
////        Db::startTrans();
////        try {
////            \app\admin\model\User::update(['is_post' => 1],['id' => $user->id]);
////            Db::commit();
////        }catch (ValidateException|PDOException|Exception $e) {
////            Db::rollback();
////            $this->error($e->getMessage());
////        }
////
////        $this->success(__('开通成功'));
////    }
    //发帖
    public function post()
    {
        $data = $this->request->post();
        $rule = [
            'content' => 'require',
            'evaluate' => 'require',
            'image' => 'require',
        ];
        $msg = [
            'content.require' => '描述不为空',
            'evaluate.require' => '评价不为空',
            'image.require' => '图片不为空',
        ];

        $validate = new \think\Validate($rule, $msg);

        $res = $validate->check($data);
        if ($res === false) {
            $this->error($validate->getError());
        }
        Db::startTrans();
        try {
            $data['user_id'] = $this->auth->id;

            Post::create($data);
            Db::commit();
        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }

    public function postlist()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit',LIMIT);

        $model = new Post();
        $list = $model->where(['user_id' => $this->auth->id])->paginate($limit,false,['page' => $page]);

        $result = array("total" => $list->total(), "rows" => $list->items());
        $this->success('返回成功',$result);
    }

    //解锁vip套餐
    public function getvip()
    {
        $id = $this->request->post('id');
        //是否开通
//        $this->error('已开通');
        $data = \app\common\model\User::getVip();
        $info = [];
        foreach ($data as $item) {
            if($item['id'] == $id) {
                $info = $item;
            }
        }
        if(empty($info)) $this->error('参数错误');

        Db::startTrans();
        try {
            $order_no = generate_sn((new \app\common\model\UserVip()), 'order_no');//订单号
            $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
            $amount = $info['price'];
            $data = [
                'user_id' => $this->auth->id,
                'order_no' => $order_no,
                'vip_id' => $id,
                'money' => $amount,
                'memo' => '',
                'paytime' => time(),
                'out_trade_no' => $out_trade_no
            ];
            UserVip::create($data);

            //支付
            //订单标题
            $title = '购买VIP套餐';
            //支付类型
            $type = "wechat";
            //支付应用
            $method = "miniapp";
            $third = Third::get(['user_id' => $this->auth->id]);
            $openid = $third->openid;
            //回调链接
            $notifyurl = $this->request->root(true) . '/addons/epay/index/vipnotifyx/paytype/' . $type;
            $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
            $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method, $openid);

            Db::commit();
        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('返回成功',$response);
    }

    //充值
    public function recharge()
    {
        $recharge_id = $this->request->post('recharge_id');
        $recharge = Recharge::get($recharge_id);
        if(empty($recharge))  $this->error('充值失败');

        Db::startTrans();
        try {
            $pay_amount = $recharge->price;
            $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
            $title = $recharge->name.'充值';
            $model = new UserRecharge();
            $model->save([
                'order_no' => generate_sn((new \app\common\model\UserRecharge()), 'order_no'),//订单号
                'out_trade_no' => $out_trade_no,
                'user_id' => $this->auth->id,
                'recharge_id' => $recharge_id,
                'price' => $pay_amount,
                'money' => $recharge->money,
                'memo' => $title,
                'pay_status' => 0
            ]);

            //支付
            //支付金额
            $amount = $pay_amount;
            //订单号
            //订单标题
//            $title = $title;
            //支付类型
            $type = "wechat";
            //支付应用
            $method = "miniapp";
            $third = Third::get(['user_id' => $this->auth->id]);
            $openid = $third->openid;
            //回调链接
            $notifyurl = $this->request->root(true) . '/addons/epay/index/rgnotifyx/paytype/' . $type;
            $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
            $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method, $openid);

            Db::commit();
        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success(__('保存成功'),$response);
    }

    //充值列表
    public function rechargelist()
    {
        $list =  Recharge::all();

        $this->success(__('保存成功'),$list);
    }

    //绑定上下级关系
    public function bindparent()
    {
        $p_id = $this->request->get('p_id');

        if(!empty($this->auth->p_id)) {
            $this->error(__('已绑定'));
        }
        $income =UserIncome::get(['user_id' =>$p_id]);

        if(empty($income)) $this->error('请申请推广');
        if($income->check_state == 0 || $income->check_state == 2) $this->error('当前推广正在申请中或已拒绝');
        if($p_id == $this->auth->id) {
            $this->error(__('绑定有误'));
        }
        $user = \app\common\model\User::get($this->auth->id);
        Db::startTrans();
        try {
            $user->save([
                'p_id' => $p_id,
                'sharetime' => time()
            ]);
            \app\common\model\Message::setMessage($p_id,"{$user->nickname}通过您的分享链接",'/pages/mine/index');
            //设置推广人数积累
            $income->setInc('share_num');
            //设置推广元宝数量
            $money = 100;
            \app\common\model\UserIncome::money($money ,$income->user_id,"{$user->nickname}通过您的分享链接得到{$money}元宝");

            Db::commit();
        }catch (ValidateException|PDOException|Exception $e) {
             Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success(__('绑定成功'));
    }

    public function moneylist()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $model = new MoneyLog();
        $list =  $model->where(['user_id' => $this->auth->id])->order('id desc')->paginate($limit,false,['page' => $page]);

        $result = array("total" => $list->total(), "rows" => $list->items());
        $this->success('返回成功',$result);
    }
}
